/*
 * WPA Supplicant / EAP-FAST (draft-cam-winget-eap-fast-00.txt)
 * Copyright (c) 2004, Jouni Malinen <jkmaline@cc.hut.fi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * Alternatively, this software may be distributed under the terms of BSD
 * license.
 *
 * See README and COPYING for more details.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>

#include "common.h"
#include "eap_i.h"
#include "eap_tls_common.h"
#include "wpa_supplicant.h"
#include "config.h"
#include "tls.h"
#include "eap_tlv.h"
#include "sha1.h"

/* TODO:
 * provisioning
 * PAC-Opaque as TLS extension
 * PAC file parsing
 */

#define EAP_FAST_VERSION 1


static void eap_fast_deinit(struct eap_sm *sm, void *priv);


struct eap_fast_key_block {
	u8 client_write_MAC_secret[20];
	u8 server_write_MAC_secret[20];
	u8 client_write_key[16];
	u8 server_write_key[16];
	u8 session_key_seed[40];
};


struct eap_fast_data {
	struct eap_ssl_data ssl;

	int fast_version;

	const struct eap_method *phase2_method;
	void *phase2_priv;
	int phase2_success;

	u8 phase2_type;
	u8 *phase2_types;
	size_t num_phase2_types;
	int resuming; /* starting a resumed session */
	struct eap_fast_key_block *key_block;
	u8 pac_key[32];
	int pac_provisioned;
	int provisioning; /* is PAC provisioning allowed */
};


static void * eap_fast_init(struct eap_sm *sm)
{
	struct eap_fast_data *data;
	struct wpa_ssid *config = eap_get_config(sm);

	data = malloc(sizeof(*data));
	if (data == NULL)
		return NULL;
	memset(data, 0, sizeof(*data));
	data->fast_version = EAP_FAST_VERSION;

	if (config && config->phase1) {
		if (strstr(config->phase1, "fast_provisioning=1")) {
			data->provisioning = 1;
			wpa_printf(MSG_DEBUG, "EAP-FAST: Automatic PAC "
				   "provisioning is allowed");
		}
	}

	if (config && config->phase2) {
		char *start, *pos, *buf;
		u8 method, *methods = NULL, *_methods;
		size_t num_methods = 0;
		start = buf = strdup(config->phase2);
		if (buf == NULL) {
			eap_fast_deinit(sm, data);
			return NULL;
		}
		while (start && *start != '\0') {
			pos = strstr(start, "auth=");
			if (pos == NULL)
				break;
			if (start != pos && *(pos - 1) != ' ') {
				start = pos + 5;
				continue;
			}

			start = pos + 5;
			pos = strchr(start, ' ');
			if (pos)
				*pos++ = '\0';
			method = eap_get_phase2_type(start);
			if (method == EAP_TYPE_NONE) {
				wpa_printf(MSG_ERROR, "EAP-FAST: Unsupported "
					   "Phase2 method '%s'", start);
			} else {
				num_methods++;
				_methods = realloc(methods, num_methods);
				if (_methods == NULL) {
					free(methods);
					eap_fast_deinit(sm, data);
					return NULL;
				}
				methods = _methods;
				methods[num_methods - 1] = method;
			}

			start = pos;
		}
		free(buf);
		data->phase2_types = methods;
		data->num_phase2_types = num_methods;
	}
	if (data->phase2_types == NULL) {
		data->phase2_types =
			eap_get_phase2_types(config, &data->num_phase2_types);
	}
	if (data->phase2_types == NULL) {
		wpa_printf(MSG_ERROR, "EAP-FAST: No Phase2 method available");
		eap_fast_deinit(sm, data);
		return NULL;
	}
	wpa_hexdump(MSG_DEBUG, "EAP-FAST: Phase2 EAP types",
		    data->phase2_types, data->num_phase2_types);
	data->phase2_type = EAP_TYPE_NONE;

	if (config->private_key) {
		/* TODO: read PAC-Key and PAC-Opaque. Set pac_provisioned=1
		 * only if PAC was available. */
		data->pac_provisioned = 1;
	}

	if (eap_tls_ssl_init(sm, &data->ssl, config)) {
		wpa_printf(MSG_INFO, "EAP-FAST: Failed to initialize SSL.");
		eap_fast_deinit(sm, data);
		return NULL;
	}

	if (data->pac_provisioned) {
		/* TODO: add PAC-Opaque as TLS Client Hello extension. */
	} else if (data->provisioning) {
		wpa_printf(MSG_DEBUG, "EAP-FAST: No PAC available - starting "
			   "provisioning");
		if (tls_connection_set_anon_dh(sm->ssl_ctx, data->ssl.conn)) {
			wpa_printf(MSG_INFO, "EAP-FAST: Could not configure "
				   "anonymous DH for TLS connection");
			eap_fast_deinit(sm, data);
			return NULL;
		}
	} else {
		wpa_printf(MSG_INFO, "EAP-FAST: No PAC configured and "
			   "provisioning disabled");
		eap_fast_deinit(sm, data);
		return NULL;
	}

	return data;
}


static void eap_fast_deinit(struct eap_sm *sm, void *priv)
{
	struct eap_fast_data *data = priv;
	if (data == NULL)
		return;
	if (data->phase2_priv && data->phase2_method)
		data->phase2_method->deinit(sm, data->phase2_priv);
	free(data->phase2_types);
	free(data->key_block);
	eap_tls_ssl_deinit(sm, &data->ssl);
	free(data);
}


static int eap_fast_encrypt(struct eap_sm *sm, struct eap_fast_data *data,
			    int id, u8 *plain, size_t plain_len,
			    u8 **out_data, size_t *out_len)
{
	int res;
	u8 *pos;
	struct eap_hdr *resp;

	/* TODO: add support for fragmentation, if needed. This will need to
	 * add TLS Message Length field, if the frame is fragmented. */
	resp = malloc(sizeof(struct eap_hdr) + 2 + data->ssl.tls_out_limit);
	if (resp == NULL)
		return 0;

	resp->code = EAP_CODE_RESPONSE;
	resp->identifier = id;

	pos = (u8 *) (resp + 1);
	*pos++ = EAP_TYPE_FAST;
	*pos++ = data->fast_version;

	res = tls_connection_encrypt(sm->ssl_ctx, data->ssl.conn,
				     plain, plain_len,
				     pos, data->ssl.tls_out_limit);
	if (res < 0) {
		wpa_printf(MSG_INFO, "EAP-FAST: Failed to encrypt Phase 2 "
			   "data");
		free(resp);
		return 0;
	}

	*out_len = sizeof(struct eap_hdr) + 2 + res;
	resp->length = htons(*out_len);
	*out_data = (u8 *) resp;
	return 0;
}


static int eap_fast_phase2_nak(struct eap_sm *sm,
			       struct eap_fast_data *data,
			       struct eap_hdr *hdr,
			       u8 **resp, size_t *resp_len)
{
	struct eap_hdr *resp_hdr;
	u8 *pos = (u8 *) (hdr + 1);

	wpa_printf(MSG_DEBUG, "EAP-FAST: Phase 2 Request: Nak type=%d", *pos);
	wpa_hexdump(MSG_DEBUG, "EAP-FAST: Allowed Phase2 EAP types",
		    data->phase2_types, data->num_phase2_types);
	*resp_len = sizeof(struct eap_hdr) + 1 + data->num_phase2_types;
	*resp = malloc(*resp_len);
	if (*resp == NULL)
		return -1;

	resp_hdr = (struct eap_hdr *) (*resp);
	resp_hdr->code = EAP_CODE_RESPONSE;
	resp_hdr->identifier = hdr->identifier;
	resp_hdr->length = htons(*resp_len);
	pos = (u8 *) (resp_hdr + 1);
	*pos++ = EAP_TYPE_NAK;
	memcpy(pos, data->phase2_types, data->num_phase2_types);

	return 0;
}


static int eap_fast_derive_msk(struct eap_sm *sm, struct eap_fast_data *data)
{
	u8 isk[32];
	u8 imck[60];

	if (data->key_block == NULL)
		return -1;

	free(sm->eapKeyData);
	sm->eapKeyData = malloc(64);
	if (sm->eapKeyData == NULL) {
		sm->eapKeyDataLen = 0;
		return -1;
	}
	sm->eapKeyDataLen = 64;
	memset(isk, 0, sizeof(isk));
	sha1_t_prf(data->key_block->session_key_seed,
		   sizeof(data->key_block->session_key_seed),
		   "Inner Methods Compound Keys",
		   isk, sizeof(isk), imck, sizeof(imck));
	sha1_t_prf(imck, 40, "Session Key Generating Function", "", 0,
		   sm->eapKeyData, sm->eapKeyDataLen);

	wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: Derived key (MSK)",
			sm->eapKeyData, sm->eapKeyDataLen);

	return 0;
}


static int eap_fast_set_tls_master_secret(struct eap_sm *sm,
					  struct eap_fast_data *data)
{
	struct tls_keys keys;
	u8 master_secret[48], *seed;
	size_t seed_len;

	if (!data->pac_provisioned ||
	    tls_connection_get_keys(sm->ssl_ctx, data->ssl.conn, &keys))
		return 0;

	wpa_hexdump(MSG_DEBUG, "EAP-FAST: client_random",
		    keys.client_random, keys.client_random_len);
	wpa_hexdump(MSG_DEBUG, "EAP-FAST: server_random",
		    keys.server_random, keys.server_random_len);

	seed_len = keys.client_random_len + keys.server_random_len;
	seed = malloc(seed_len);
	if (seed == NULL)
		return -1;
	memcpy(seed, keys.client_random, keys.client_random_len);
	memcpy(seed + keys.client_random_len, keys.server_random,
	       keys.server_random_len);

	/* master_secret = T-PRF(PAC-Key, "PAC to master secret label hash", 
	 * server_random + client_random, 48) */
	sha1_t_prf(data->pac_key, sizeof(data->pac_key),
		   "PAC to master secret label hash",
		   seed, seed_len, master_secret, sizeof(master_secret));
	free(seed);
	wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: TLS pre-master-secret",
			master_secret, sizeof(master_secret));

	return tls_connection_set_master_key(sm->ssl_ctx, data->ssl.conn,
					     master_secret,
					     sizeof(master_secret));
}


static int eap_fast_phase2_request(struct eap_sm *sm,
				   struct eap_fast_data *data,
				   struct eap_hdr *req,
				   struct eap_hdr *hdr,
				   u8 **resp, size_t *resp_len)
{
	size_t len = ntohs(hdr->length);
	u8 *pos;

	if (len <= sizeof(struct eap_hdr)) {
		wpa_printf(MSG_INFO, "EAP-FAST: too short "
			   "Phase 2 request (len=%d)", len);
		return -1;
	}
	pos = (u8 *) (hdr + 1);
	wpa_printf(MSG_DEBUG, "EAP-FAST: Phase 2 Request: type=%d", *pos);
	switch (*pos) {
	case EAP_TYPE_IDENTITY:
		*resp = eap_sm_buildIdentity(sm, req->identifier, resp_len, 1);
		break;
	case EAP_TYPE_TLV:
		if (eap_tlv_process(sm, hdr, resp, resp_len))
			return -1;
		if (sm->methodState == METHOD_DONE &&
		    sm->decision == DECISION_UNCOND_SUCC)
			eap_fast_derive_msk(sm, data);
		break;
	default:
		if (data->phase2_type == EAP_TYPE_NONE) {
			int i;
			for (i = 0; i < data->num_phase2_types; i++) {
				if (data->phase2_types[i] != *pos)
					continue;

				data->phase2_type = *pos;
				wpa_printf(MSG_DEBUG, "EAP-FAST: Selected "
					   "Phase 2 EAP method %d",
					   data->phase2_type);
				break;
			}
		}
		if (*pos != data->phase2_type || *pos == EAP_TYPE_NONE) {
			if (eap_fast_phase2_nak(sm, data, hdr, resp, resp_len))
				return -1;
			return 0;
		}

		if (data->phase2_priv == NULL) {
			data->phase2_method = eap_sm_get_eap_methods(*pos);
			if (data->phase2_method) {
				sm->init_phase2 = 1;
				data->phase2_priv =
					data->phase2_method->init(sm);
				sm->init_phase2 = 0;
			}
		}
		if (data->phase2_priv == NULL || data->phase2_method == NULL) {
			wpa_printf(MSG_INFO, "EAP-FAST: failed to initialize "
				   "Phase 2 EAP method %d", *pos);
			sm->methodState = METHOD_DONE;
			sm->decision = DECISION_FAIL;
			sm->ignore = TRUE;
			return -1;
		}
		*resp = data->phase2_method->process(sm, data->phase2_priv,
						     (u8 *) hdr, len,
						     resp_len);
		/* Don't allow Phase 2 to mark negotiation completed,
		 * since Acknowledged Result is expected. */
		if (sm->methodState == METHOD_DONE &&
		    sm->decision == DECISION_UNCOND_SUCC) {
			data->phase2_success = 1;
			sm->methodState = METHOD_CONT;
			sm->decision = DECISION_COND_SUCC;
		}
		break;
	}
	return 0;
}


static int eap_fast_decrypt(struct eap_sm *sm,
			    struct eap_fast_data *data, struct eap_hdr *req,
			    u8 *in_data, size_t in_len,
			    u8 **out_data, size_t *out_len)
{
	u8 *in_decrypted;
	int buf_len, len_decrypted, len, res;
	struct eap_hdr *hdr;
	u8 *resp = NULL;
	size_t resp_len;
	int no_tlv_eap_hdr = 0;

	wpa_printf(MSG_DEBUG, "EAP-FAST: received %d bytes encrypted data for "
		   "Phase 2", in_len);

	res = eap_tls_data_reassemble(sm, &data->ssl, &in_data, &in_len);
	if (res < 0 || res == 1)
		return res;

	buf_len = in_len;
	if (data->ssl.tls_in_total > buf_len)
		buf_len = data->ssl.tls_in_total;
	in_decrypted = malloc(buf_len);
	if (in_decrypted == NULL) {
		free(data->ssl.tls_in);
		data->ssl.tls_in = NULL;
		data->ssl.tls_in_len = 0;
		wpa_printf(MSG_WARNING, "EAP-FAST: failed to allocate memory "
			   "for decryption");
		return -1;
	}

	len_decrypted = tls_connection_decrypt(sm->ssl_ctx, data->ssl.conn,
					       in_data, in_len,
					       in_decrypted, buf_len);
	free(data->ssl.tls_in);
	data->ssl.tls_in = NULL;
	data->ssl.tls_in_len = 0;
	if (len_decrypted < 0) {
		wpa_printf(MSG_INFO, "EAP-FAST: Failed to decrypt Phase 2 "
			   "data");
		free(in_decrypted);
		return 0;
	}

	wpa_hexdump(MSG_DEBUG, "EAP-FAST: Decrypted Phase 2 EAP", in_decrypted,
		    len_decrypted);

	hdr = (struct eap_hdr *) in_decrypted;
	if (!no_tlv_eap_hdr) {
		struct eap_hdr *nhdr = malloc(sizeof(struct eap_hdr) +
					      len_decrypted);
		if (nhdr == NULL) {
			free(in_decrypted);
			return 0;
		}
		memcpy((u8 *) (nhdr + 1), in_decrypted, len_decrypted);
		free(in_decrypted);
		nhdr->code = req->code;
		nhdr->identifier = req->identifier;
		nhdr->length = htons(sizeof(struct eap_hdr) + len_decrypted);

		len_decrypted += sizeof(struct eap_hdr);
		in_decrypted = (u8 *) nhdr;
	}
	hdr = (struct eap_hdr *) in_decrypted;
	if (len_decrypted < sizeof(*hdr)) {
		free(in_decrypted);
		wpa_printf(MSG_INFO, "EAP-FAST: Too short Phase 2 "
			   "EAP frame (len=%d)", len_decrypted);
		return 0;
	}
	len = ntohs(hdr->length);
	if (len > len_decrypted) {
		free(in_decrypted);
		wpa_printf(MSG_INFO, "EAP-FAST: Length mismatch in "
			   "Phase 2 EAP frame (len=%d hdr->length=%d)",
			   len_decrypted, len);
		return 0;
	}
	if (len < len_decrypted) {
		wpa_printf(MSG_INFO, "EAP-FAST: Odd.. Phase 2 EAP header has "
			   "shorter length than full decrypted data (%d < %d)",
			   len, len_decrypted);
	}
	wpa_printf(MSG_DEBUG, "EAP-FAST: received Phase 2: code=%d "
		   "identifier=%d length=%d", hdr->code, hdr->identifier, len);
	switch (hdr->code) {
	case EAP_CODE_REQUEST:
		if (eap_fast_phase2_request(sm, data, req, hdr,
					    &resp, &resp_len)) {
			free(in_decrypted);
			wpa_printf(MSG_INFO, "EAP-FAST: Phase2 Request "
				   "processing failed");
			return 0;
		}
		break;
	case EAP_CODE_SUCCESS:
		wpa_printf(MSG_DEBUG, "EAP-FAST: Phase 2 Success");
		/* FIX: ? */
		break;
	case EAP_CODE_FAILURE:
		wpa_printf(MSG_DEBUG, "EAP-FAST: Phase 2 Failure");
		/* FIX: ? */
		break;
	default:
		wpa_printf(MSG_INFO, "EAP-FAST: Unexpected code=%d in "
			   "Phase 2 EAP header", hdr->code);
		break;
	}

	free(in_decrypted);

	if (resp) {
		u8 *resp_pos;
		size_t resp_send_len;

		wpa_hexdump(MSG_DEBUG, "EAP-FAST: Encrypting Phase 2 data",
			    resp, resp_len);
		if (no_tlv_eap_hdr) {
			resp_pos = resp + sizeof(struct eap_hdr);
			resp_send_len = resp_len - sizeof(struct eap_hdr);
		} else {
			resp_pos = resp;
			resp_send_len = resp_len;
		}

		if (eap_fast_encrypt(sm, data, req->identifier,
				     resp_pos, resp_send_len,
				     out_data, out_len)) {
			wpa_printf(MSG_INFO, "EAP-FAST: Failed to encrypt "
				   "a Phase 2 frame");
		}
		free(resp);
	}

	return 0;
}


static u8 * eap_fast_process(struct eap_sm *sm, void *priv,
			     u8 *reqData, size_t reqDataLen,
			     size_t *respDataLen)
{
	struct eap_hdr *req;
	int left, res;
	unsigned int tls_msg_len;
	u8 flags, *pos, *resp, id;
	struct eap_fast_data *data = priv;

	if (tls_get_errors(sm->ssl_ctx)) {
		wpa_printf(MSG_INFO, "EAP-FAST: TLS errors detected");
		sm->ignore = TRUE;
		return NULL;
	}

	req = (struct eap_hdr *) reqData;
	pos = (u8 *) (req + 1);
	if (reqDataLen < sizeof(*req) + 2 || *pos != EAP_TYPE_FAST ||
	    (left = htons(req->length)) > reqDataLen) {
		wpa_printf(MSG_INFO, "EAP-FAST: Invalid frame");
		sm->ignore = TRUE;
		return NULL;
	}
	left -= sizeof(struct eap_hdr);
	id = req->identifier;
	pos++;
	flags = *pos++;
	left -= 2;
	wpa_printf(MSG_DEBUG, "EAP-FAST: Received packet(len=%d) - "
		   "Flags 0x%02x", reqDataLen, flags);
	if (flags & EAP_TLS_FLAGS_LENGTH_INCLUDED) {
		if (left < 4) {
			wpa_printf(MSG_INFO, "EAP-FAST: Short frame with TLS "
				   "length");
			sm->ignore = TRUE;
			return NULL;
		}
		tls_msg_len = (pos[0] << 24) | (pos[1] << 16) | (pos[2] << 8) |
			pos[3];
		wpa_printf(MSG_DEBUG, "EAP-FAST: TLS Message Length: %d",
			   tls_msg_len);
		if (data->ssl.tls_in_left == 0) {
			data->ssl.tls_in_total = tls_msg_len;
			data->ssl.tls_in_left = tls_msg_len;
			free(data->ssl.tls_in);
			data->ssl.tls_in = NULL;
			data->ssl.tls_in_len = 0;
		}
		pos += 4;
		left -= 4;
	}

	sm->ignore = FALSE;

	sm->methodState = METHOD_CONT;
	sm->decision = DECISION_COND_SUCC;
	sm->allowNotifications = TRUE;

	if (flags & EAP_TLS_FLAGS_START) {
		wpa_printf(MSG_DEBUG, "EAP-FAST: Start (server ver=%d, own "
			   "ver=%d)", flags & EAP_PEAP_VERSION_MASK,
			data->fast_version);
		if ((flags & EAP_PEAP_VERSION_MASK) < data->fast_version)
			data->fast_version = flags & EAP_PEAP_VERSION_MASK;
		wpa_printf(MSG_DEBUG, "EAP-FAST: Using FAST version %d",
			   data->fast_version);
		/* FIX: A-ID should be in A-ID TLV (at least Type+Len) */
		wpa_hexdump_ascii(MSG_DEBUG, "EAP-FAST: A-ID", pos, left);
		/* TODO: verify that A-ID matches with server identity */
		left = 0; /* A-ID is not used in further packet processing */
	}

	resp = NULL;
	if (tls_connection_established(sm->ssl_ctx, data->ssl.conn) &&
	    !data->resuming) {
		res = eap_fast_decrypt(sm, data, req, pos, left,
				       &resp, respDataLen);
	} else {
		res = eap_tls_process_helper(sm, &data->ssl, EAP_TYPE_FAST,
					     data->fast_version, id, pos, left,
					     &resp, respDataLen);

		eap_fast_set_tls_master_secret(sm, data);

		if (tls_connection_established(sm->ssl_ctx, data->ssl.conn)) {
			wpa_printf(MSG_DEBUG,
				   "EAP-FAST: TLS done, proceed to Phase 2");
			sm->methodState = METHOD_CONT;
			data->resuming = 0;
			free(data->key_block);
			data->key_block = (struct eap_fast_key_block *)
				eap_tls_derive_key(sm, &data->ssl,
						   "client EAP encryption",
						   sizeof(*data->key_block));
		}
	}

	if (res == 1)
		return eap_tls_build_ack(respDataLen, id, EAP_TYPE_FAST,
					 data->fast_version);
	return resp;
}


static Boolean eap_fast_has_reauth_data(struct eap_sm *sm, void *priv)
{
	struct eap_fast_data *data = priv;
	return tls_connection_established(sm->ssl_ctx, data->ssl.conn);
}


static void eap_fast_deinit_for_reauth(struct eap_sm *sm, void *priv)
{
}


static void * eap_fast_init_for_reauth(struct eap_sm *sm, void *priv)
{
	struct eap_fast_data *data = priv;
	if (eap_tls_reauth_init(sm, &data->ssl)) {
		free(data);
		return NULL;
	}
	data->phase2_success = 0;
	data->resuming = 1;
	return priv;
}


const struct eap_method eap_method_fast =
{
	.method = EAP_TYPE_FAST,
	.name = "FAST",
	.init = eap_fast_init,
	.deinit = eap_fast_deinit,
	.process = eap_fast_process,
	.has_reauth_data = eap_fast_has_reauth_data,
	.deinit_for_reauth = eap_fast_deinit_for_reauth,
	.init_for_reauth = eap_fast_init_for_reauth,
};
